package com.house.controller;

import com.house.dao.SpitDao;
import com.house.pojo.Spit;
import com.house.service.SpitService;
import com.house.util.PageUtil;
import com.house.util.Result;
import com.house.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spit")
@CrossOrigin
public class SpitController {

    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping(method = RequestMethod.GET)
    public List<Spit> findAll(){
        return spitService.findAll();
    }

    @RequestMapping(value = "/{spitId}",method = RequestMethod.GET)
    public Spit findById(@PathVariable String spitId){
        return spitService.findById(spitId);
    }

    @RequestMapping(method = RequestMethod.POST)
    public Result addspit(@RequestBody Spit spit){
        spitService.addspit(spit);
        return new Result(true, StatusCode.OK,"文章添加成功");
    }

    @RequestMapping(method = RequestMethod.PUT)
    public Result update(@RequestBody Spit spit){
        spitService.update(spit);
        return new Result(true,StatusCode.OK,"修改成功");
    }
    @RequestMapping(value = "/{spitId}",method = RequestMethod.DELETE)
    public Result update(@PathVariable String spitId){
        spitService.del(spitId);
        return new Result(true,StatusCode.OK,"删除成功");
    }
    //查询父id
    @RequestMapping(value = "/comment/{spitId}/{page}/{size}",method = RequestMethod.GET)
    public Result findByParentid(@PathVariable String spitId,@PathVariable int page,@PathVariable int size){
        Page<Spit> parentid = spitService.findByParentid(spitId, page, size);
        return new Result(true,StatusCode.OK,"查询成功",new PageUtil<Spit>(page,parentid.getTotalElements(),parentid.getContent(),size));
    }
    //点赞
    @RequestMapping(value = "/thumbup/{spitId}",method = RequestMethod.PUT)
    public Result thumbup(@PathVariable String spitId){
        //判断当前用户是否已经点赞，但是现在我们没用做认证，暂时先把userid写死
        String userid="111";
        //判断当前用户是否已经点赞
        if (redisTemplate.opsForValue().get("thumbup_"+userid)!=null){
            return new Result(false,StatusCode.REPERROR,"不能重复点赞");
        }
        spitService.thumbup(spitId);
        redisTemplate.opsForValue().set("thumbup_"+userid,1);
        return new Result(true,StatusCode.OK,"点赞成功");
    }
}
